package com.itsu.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtil {

    private static SqlSessionFactory sqlSessionFactory;

    private static ThreadLocal<SqlSession> ts = new ThreadLocal<>();


    private SqlSessionFactoryUtil() {
    }

    static {
        try {
            InputStream ras = Resources.getResourceAsStream("mybatisConfig.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(ras);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession openSession(boolean autoCommit) {
        SqlSession sqlSession = sqlSessionFactory.openSession(autoCommit);
        ts.set(sqlSession);
        return sqlSession;
    }

    public static SqlSession openSession() {
        return openSession(false);
    }

    public static void commit() {
        SqlSession sqlSession = ts.get();
        if (sqlSession != null) {
            sqlSession.commit();
        }
    }

    public static void rollback() {
        SqlSession sqlSession = ts.get();
        if (sqlSession != null) {
            sqlSession.rollback();
        }
    }

    public static void close() {
        SqlSession sqlSession = ts.get();
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

}
